<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
	  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
	  layout:decorate="~{layouts/layout}">
  <head>
    <meta charset="utf-8">
    <title>电子病历内容操作</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<script th:inline="javascript">

		// 获取模板数据
		var mrContent = [[${mrContent}]];
		var medicalRecord = [[${medicalRecord}]];

		// 解析内容并渲染模板值
		function parseContentAndRender() {
			debugger
			mrContent.contentItemList?.forEach(function (value) {
				console.log(value)
				const elementById = document.getElementById(value.id);
				if (elementById){
					const data = value.d;
					switch(elementById.getAttribute("data-for-template")) {
						// 多选或者单选场景
						case 'checkType': case 'gender':
							elementById.checked = data.a.v;
							break;
						// 图片场景
						case 'patientImage':
							elementById.src = data.a.v.src;
							elementById.width = data.a.v.width;
							elementById.height = data.a.v.height;
							break;
						// 表格场景
						case 'tbodyTemplate':
							var tbodyHtml = '';
							// document.getElementById('tbodyTemplate').innerHTML = "<tr><td>" +"4"+"</td><td>"+"Admin"+"</td></tr>"
							// {"id":"tbodyTemplate","data":{"a":{"key":"a1","value":["1","tom"]},"b":{"key":"b1","value":["2","zss"]}}}
							Object.keys(data).forEach((key) => {
								const tbodyValue = data[key].v;
								tbodyHtml += "<tr><td>";
								tbodyValue.forEach(function (v, i) {
									if (i === 0){
										tbodyHtml += v
									}else {
										tbodyHtml += "</td><td>" + v
									}
								});
								tbodyHtml += "</td></tr>";
							});
							elementById.innerHTML = tbodyHtml;
							break;
						// 默认输入框场景
						default:
							elementById.value = value.d.a.v;
					}
				}
			})
		}

		// 包装内容
		function wrapperContent(formData) {
			const contentArray = [];
			Object.keys(formData).forEach((key) => {
				switch(key) {
					// 多选或者单选场景
					case 'checkType': case 'gender':
						formData[key].forEach(function (v) {
							contentArray.push({
								"id": v.id,
								"d": {
									"a": {
										"k":"a1",
										"v":v.checked
									}
								}
							})
						});
						delete formData[key];
						break;
					// 图片场景
					case 'patientImage':
						const imageData = formData[key];
						contentArray.push({
							"id": imageData.id,
							"d": {
								"a": {
									"k":"a1",
									"v": imageData
								}
							}
						});
						break;
					// 表格场景
					// document.getElementById('tbodyTemplate').innerHTML = "<tr><td>" +"4"+"</td><td>"+"Admin"+"</td></tr>"
					// {"id":"tbodyTemplate","data":{"a":{"key":"a1","value":["1","tom"]},"b":{"key":"b1","value":["2","zss"]}}}
					case 'tbodyTemplate':
						const content = {
							"id": key,
							"d": {}
						}
						var tbodyHtml = document.getElementById(key).innerHTML;
						var tbodyRows = tbodyHtml?.replaceAll("<tr>","").replaceAll("<td>","").split("</tr>");
						// 去掉最后一个空的多余数据
						tbodyRows.pop();
						tbodyRows.forEach((row, i) => {
							const rowCells = row.split("</td>");
							// 去掉最后一个空的多余数据
							rowCells.pop();
							const rowKey = "" + i;
							content.d[rowKey] = {
								"k":rowKey,
								"v":rowCells
							}
						});
						contentArray.push(content);
						break;
					// 默认输入框场景
					default:
						contentArray.push({
							"id": key,
							"d": {
								"a": {
									"k":"a1",
									"v":formData[key]
								}
							}
						});
				}
			});
			return contentArray;
		}

		// 保存病历内容
		function saveMrContent() {
			// 获取表单数据
			var formData = getFormData();
			// 包装内容
			var contentArray = wrapperContent(formData);
			var data = {
				"recordId": medicalRecord.id,
				"fromRevision": mrContent.revision ? mrContent.revision : 0,
				"content": JSON.stringify(contentArray)
			}
			console.log(data)
			debugger
			$.ajax({
				url: "mrContent/save",
				type: "post",
				contentType: "application/json",
				dataType: "json",
				async: false,
				data: JSON.stringify(data),
				beforeSend: function () {},
				success: function(result) {
					console.log("result: ", result)
					const msg = EmrResultCode.getMessageByCode(result.code, result.msg);
					if (result.code === 200){
						alert(msg);
						history.go(0)
					}else {
						alert(msg);
					}

				}
			})
		}

		// 完成/取消病历
		function completeMrContent(completeAction) {
			console.log("完成/取消病历"+ completeAction)
			var data = {
			  "recordId": medicalRecord.id,
			  "fromRevision": mrContent.revision,
			  "publish": completeAction
			}

			$.ajax({
			  url: "mrContent/complete",
			  type: "post",
			  contentType: "application/json",
			  dataType: "json",
			  data: JSON.stringify(data),
			  beforeSend: function () {},
			  success: function(result) {
				  console.log("result: ", result);
				  const msg = EmrResultCode.getMessageByCode(result.code, result.msg);
				  if (result.code === 200){
					  alert(msg);
					  history.go(0)
				  }else {
					  alert(msg);
				  }

			  }
			})
		}

		// 打印病历
		function printMrContent() {
		  	console.log("打印病历")
			var data = {
				"recordId": medicalRecord.id,
				"fromRevision": mrContent.revision,
			}

			$.ajax({
				url: "mrContent/print",
				type: "post",
				contentType: "application/json",
				dataType: "json",
				data: JSON.stringify(data),
				beforeSend: function () {},
				success: function(result) {
					console.log("result: ", result);
					const msg = EmrResultCode.getMessageByCode(result.code, result.msg);
					if (result.code === 200){
						alert(msg);
						history.go(0)
					}else {
						alert(msg);
					}
				}
			})
		}

		// 获取图像数据
		function selectImgData(id) {
			var elementById = document.getElementById(id);
			return {"id": elementById.id, "name": elementById.name, "src": elementById.src,
				"width": elementById.width,
				"height": elementById.height
			}
		}

		// 获取复选框的数据
		function selectCheckedArray(name) {
			var checkedArray = [];
			$('input:checkbox[name="' + name + '"]:checked').each(function(i, obj) {
				console.log(obj);
				checkedArray.push({"id": obj.id, "name": obj.name, "checked": obj.checked})
			});
			return checkedArray;
		}

		// 获取单选框的数据
		function selectRadioChecked(name) {
			var checkedArray = [];
			$('input[name="' + name + '"]:checked').each(function(i, obj) {
				console.log(obj);
				checkedArray.push({"id": obj.id, "name": obj.name, "checked": obj.checked})
			});
			return checkedArray;
		}

	</script>
  </head>
  <body>
	<th:block layout:fragment="content">
		<div class="span9">
			<div class="row-fluid">
				<div class="page-header">
					<h1>电子病历内容操作 <small th:text="'内容版本号: ' + (${mrContent.revision} ? ${mrContent.revision} : 0)"></small></h1>
				</div>
				<div th:replace="${mrTemplate.resource} :: ${mrTemplate.fragmentName}">
					<p>medical record write will be replaced...</p>
				</div>
				<input type="submit" class="btn btn-primary btn-large" value="保存病历" onclick="saveMrContent()" />
				<input type="submit" class="btn btn-success btn-large" value="完成病历" onclick="completeMrContent(1)" />
				<input type="submit" class="btn btn-danger btn-large" value="取消完成" onclick="completeMrContent(0)" />
				<input type="submit" class="btn btn-info btn-large" value="打印病历" onclick="printMrContent()" />
				<a class="btn" th:href="@{/emr-list}">Cancel</a>
			</div>
		</div>
	</th:block>
  </body>
</html>
